import { extend, pick } from "lodash";
import { useCallback } from "react";
import DuplicateQueryDialog from "@/components/queries/DuplicateQueryDialog"
import url from "url";
import qs from "query-string";
import { Query } from "@/services/query";
import navigateTo from "@/components/ApplicationArea/navigateTo";

function keepCurrentUrlParams(targetUrl) {
  const currentUrlParams = qs.parse(window.location.search);
  targetUrl = url.parse(targetUrl);
  const targetUrlParams = qs.parse(targetUrl.search);
  return url.format(
    extend(pick(targetUrl, ["protocol", "auth", "host", "pathname", "hash"]), {
      search: qs.stringify(extend(currentUrlParams, targetUrlParams)),
    })
  );
}

export default function useDuplicateQueryDialog(query) {

  return useCallback(() => {
    DuplicateQueryDialog.showModal({ query }).onClose(({name, dataSourceId}) => {
      Query.fork({ id: query.id, name, dataSourceId })
      .then(newQuery => {
        navigateTo(keepCurrentUrlParams(newQuery.getUrl(true)));
      })
    })
  }, [query]);
}
